package com.quan.web.controller.weixin;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quan.common.annotation.RequiresPermissions;
import com.quan.common.base.pojo.JSONResult;
import com.quan.common.base.pojo.PageBean;
import com.quan.common.core.support.BaseController;
import com.quan.sdk.weixin.tools.MediaTools;
import com.quan.weixin.rpc.api.WeixinMaterialService;
import com.quan.weixin.rpc.model.WeixinMaterial;

@RestController
@RequestMapping(value = "/api/weixin/material")
public class WeixinMaterialController extends BaseController {

	@Autowired
	private WeixinMaterialService weixinMaterialService;

	@RequiresPermissions(value="weixin:material:add", description="添加微信素材列表")
	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody WeixinMaterial entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return JSONResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinMaterialService.insertSelective(entity);

		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:material:delete", description="删除微信素材列表")
	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		this.weixinMaterialService.deleteById(Integer.valueOf(id.toString()));
		return JSONResult.ok();
	}
	
	@RequiresPermissions(value="weixin:material:delete", description="删除微信素材列表")
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String ids) {
		this.weixinMaterialService.deleteByIds(ids) ;
		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:material:update", description="修改微信素材列表")
	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinMaterial entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return JSONResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		this.weixinMaterialService.update(entity);
		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:material:detail", description="查询微信素材列表详情")
	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		System.out.println(this.weixinMaterialService);
		return this.weixinMaterialService.selectOneById(id);
	}
	
	@RequiresPermissions(value="weixin:material:list", description="查询微信素材列表")
	@GetMapping(value = "/list")
	public Object list(WeixinMaterial entity) {
		JSONObject materialList = MediaTools.getMaterialList("news", 0, 20) ;
		JSONArray jsonArray = materialList.getJSONArray("item");
		for (Object object : jsonArray) {
			JSONObject parseObject = JSON.parseObject(object.toString()) ;
			System.out.println(parseObject.getString("media_id"));
			
			//图文
			String content = parseObject.getString("content");
			JSONObject contentObject = JSON.parseObject(content) ;
			JSONArray parseArray = JSON.parseArray(contentObject.getString("news_item")) ;
			for (Object newsItem : parseArray) {
				JSONObject news = JSON.parseObject(newsItem.toString()) ;
				System.out.println(news.getString("title")+"=="+news.getString("url"));
			}
		}
		
		return this.weixinMaterialService.selectPage(entity, new PageBean(request)) ;
	}
	
	/**
	 * 同步素材列表
	 */
	@RequiresPermissions(value="weixin:material:sync", description="同步素材列表")
	@GetMapping(value = "/syncMaterial")
	public void syncMaterial() {
		//素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
		String[] type = new String[]{"image", "video", "voice", "news"};
		
		for (String t : type) {
			JSONObject materialList = MediaTools.getMaterialList(t, 0, 20) ;
			JSONArray jsonArray = materialList.getJSONArray("item");
			for (Object object : jsonArray) {
				JSONObject parseObject = JSON.parseObject(object.toString()) ;
				String mediaId = parseObject.getString("media_id") ;
				
				if("news".equals(t)) { //图文
					if(this.weixinMaterialService.existValue(WeixinMaterial.class, "mediaId", mediaId) > 0) {
						continue ;
					} else {
						String content = parseObject.getString("content");
						JSONObject contentObject = JSON.parseObject(content) ;
						JSONArray parseArray = JSON.parseArray(contentObject.getString("news_item")) ;
						
						//获取图文的第一条记录
						String first = parseArray.getString(0) ;
						JSONObject news = JSON.parseObject(first.toString()) ;
						
						WeixinMaterial wm = new WeixinMaterial() ;
						wm.setType(t);
						wm.setMediaId(mediaId);
						wm.setTitle(news.getString("title"));
						wm.setUrl(news.getString("url"));
						
						//判断是否有多条图文(跳过第一条图文)
						if(parseArray.size() > 1) {
							List<String> subList = new ArrayList<String>() ;
							
							for(int i=1; i<parseArray.size(); i++) {
								String items = parseArray.getString(i) ;
								JSONObject newsSub = JSON.parseObject(items) ;
								subList.add(newsSub.getString("title")+","+newsSub.getString("url")) ;
							}
							
							wm.setSubNews(JSON.toJSONString(subList));
						}
						
						this.weixinMaterialService.insertSelective(wm) ;
					}
					
				} else {
					if(this.weixinMaterialService.existValue(WeixinMaterial.class, "mediaId", mediaId) > 0) {
						continue ;
					} else {
						WeixinMaterial wm = new WeixinMaterial() ;
						wm.setMediaId(mediaId);
						wm.setType(t);
						wm.setTitle(parseObject.getString("name"));
						wm.setUrl(parseObject.getString("url"));
						
						this.weixinMaterialService.insertSelective(wm) ;
					}
				}
				
			}
		}
		
		/*JSONObject materialList = MediaTools.getMaterialList("news", 0, 20) ;
		JSONArray jsonArray = materialList.getJSONArray("item");
		for (Object object : jsonArray) {
			JSONObject parseObject = JSON.parseObject(object.toString()) ;
			System.out.println(parseObject.getString("media_id"));
			
			//图文
			String content = parseObject.getString("content");
			JSONObject contentObject = JSON.parseObject(content) ;
			JSONArray parseArray = JSON.parseArray(contentObject.getString("news_item")) ;
			for (Object newsItem : parseArray) {
				JSONObject news = JSON.parseObject(newsItem.toString()) ;
				System.out.println(news.getString("title")+"=="+news.getString("url"));
			}
		}*/
	}
	
}
